<?php

namespace backend\modules\supplier\models;

use Yii;

/**
 * 这个模型基于表 "{{%s_storage_rack}}" 生成.
 *
 * @property integer $id
 * @property string $name
 * @property integer $storage_id
 * @property integer $supplier_id
 * @property integer $sort
 */
class Rack extends \common\models\AR {

    public $modelName = '';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%s_storage_rack}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'storage_id', 'supplier_id'], 'required'],
            [['name'], 'unique'],
            [['storage_id', 'supplier_id', 'sort'], 'integer'],
            [['name'], 'string', 'max' => 25],
            [['sort'], 'default', 'value' => 0]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '名称',
            'storage_id' => '仓库',
            'supplier_id' => '供应商ID',
            'sort' => '排序',
        ];
    }

    public function beforeValidate() {
        if (parent::beforeValidate()) {
            $this->supplier_id = Yii::$app->user->identity->supplier_id;
            return true;
        } else {
            return FALSE;
        }
    }

    /**
     * 引用仓库信息
     * @return Storage
     */
    public function getStorage() {
        return $this->hasOne(Storage::className(), ['id' => 'storage_id']);
    }

    /**
     * 根据仓库ID，获取所有的货架列表
     * @param type $storage_id
     * @return array Rack
     */
    public static function getAll($storage_id = 0) {
        $param = ['supplier_id' => Yii::$app->user->identity->supplier_id];
        $storage_id > 0 && $param['storage_id'] = $storage_id;

        return self::find()->where($param)->all();
    }

    /**
     * 获取货位被引用的次数
     * @return integer 货位被引用的次数
     */
    public function getUsedAcount() {
        return $this->hasMany(Slot::className(), ['rack_id' => 'id'])->count();
    }

}
